package cmd

import (
	"dragonfly/common/config"
	"encoding/json"
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var configCmd = &cobra.Command{
	Use:   "config",
	Short: "Configuration",
	Long:  "config file is global effective. default config file is config.json.",
}

var validateConfigCmd = &cobra.Command{
	Use:   "validate",
	Short: "Validate config file",
	Long: `If the config file is valid, this command will output a success message and have a zero exit code.
If it is invalid, this command will output an error and have a non-zero exit code.
`,
	RunE: configValidateCmdFn,
}

func init() {
	configCmd.AddCommand(validateConfigCmd)
	RootCmd.AddCommand(configCmd)
}

func configValidateCmdFn(command *cobra.Command, args []string) error {
	filePath, err := command.Flags().GetString("config")
	if err != nil {
		return fmt.Errorf("Not provide config args")
	}
	filePath = config.FindConfigFile(filePath)
	file, err := os.Open(filePath)
	if err != nil {
		return fmt.Errorf("Open file %s failed. %s", filePath, err)
	}
	decoder := json.NewDecoder(file)
	cfg := config.Config{}
	err = decoder.Decode(&cfg)

	if err != nil {
		return fmt.Errorf("Decode file %s failed. %s", filePath, err)
	}
	if _, err := file.Stat(); err != nil {
		return fmt.Errorf("File %s is not found. %s", filePath, err)
	}
	if err := cfg.IsValid(); err != nil {
		return fmt.Errorf("Configure file %s is invalid. %s", filePath, err)
	}
	CommandPrettyPrintln("The document is valid")
	return nil
}
